// const serverUrl=;
const localhost=['file:///E:/Grey/Project/Html/LoldGame/index.html','file:///E:/Grey/Projects/LoldGame/index.html'].indexOf(document.baseURI)+1;
const serverUrl=['https://lold.pythonanywhere.com/game',(false? 'http://192.168.19.84/game':'http://localhost:1212/game'),'http://localhost:1212/game'][localhost];
const getAPI="/get",setAPI="/set";
const notbanned=['unlocked','count','limit','speed','bounce'];

function processGamedata(root)
{
    let processed={};
    for(let it in root)
    {
        if(notbanned.indexOf(it)!=-1)
            processed[it]=root[it];
        else if(root[it] instanceof Array)
        {
            processed[it]=new Array();
            for(let i of root[it])
                processed[it].push(processGamedata(i));
        }
        else if(root[it] instanceof Object)
            processed[it]=processGamedata(root[it]);
    }
    return processed;
}

function mergeData(root,data)
{
    let target={};
    if(!root) return data;
    for(let it in data)
    {
        if(root[it]===undefined)
            target[it]=data[it];
        else if(data[it] instanceof Array)
        {
            if(!(root[it] instanceof Array)) target[it]=data[it];
            else target[it]=new Array(data[it].length);for(let i in data[it]) target[it][i]=mergeData(root[it][i],data[it][i]);
        }
        else if(data[it] instanceof Object)
        {
            if(!(root[it] instanceof Object)) target[it]=data[it];
            else target[it]=mergeData(root[it],data[it]);
        }
        else target[it]=root[it];
    }
    // console.log("merge data",root,data,target);
    return target;
}

function uploadData(data)
{
    const encode=(data)=>{return btoa(encodeURIComponent(JSON.stringify(data)))};
    data=encode(data);
    let xhr=new XMLHttpRequest();
    xhr.open("POST",serverUrl+setAPI);
    xhr.timeout=2000;
    xhr.setRequestHeader("Content-Type","application/json");
    xhr.onreadystatechange=()=>{
        if(xhr.readyState==4&&(xhr.status==200||xhr.status==304))
        {
            document.getElementById('data-message').style.color="green";
            document.getElementById('data-message').innerHTML="Update successfully.";
            $('#data-message').fadeTo(500,1);
            $('#data-message').fadeTo(3000,0);
            console.log("update successfully.");
        }
        else if(xhr.readyState==4)
        {
            document.getElementById('data-message').style.color="red";
            document.getElementById('data-message').innerHTML="Update failed.";
            $('#data-message').fadeTo(500,1);
            $('#data-message').fadeTo(3000,0);
            console.log("ERROR : Upload failed.",xhr);
        }
    };
    xhr.send(JSON.stringify({id:(localhost? 4:id),data:data}));
    return;
}

function getData()
{
    return new Promise((resolve,reject)=>{
        let xhr=new XMLHttpRequest();
        xhr.open("POST",serverUrl+getAPI);
        xhr.timeout=2000;
        xhr.setRequestHeader("Content-Type","application/json");
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4&&(xhr.status==200||xhr.status==304))
                resolve(decodeURIComponent(atob(xhr.responseText)));
            else if(xhr.readyState==4)
                reject(xhr);
        };
        xhr.send(JSON.stringify({id:(localhost? 4:id)}));
        return;
    });
}

function fetchData()
{
    gamePaused=true;
    getData().then((body)=>{
        console.log("Fetch successfully.");
        gamedata=mergeData(JSON.parse(body),gamedata);
        centuries.innerHTML="";
        for(let i in gamedata)
            if(gamedata[i].unlocked)
            {
                centuries.innerHTML+=`<button type="button" name="${i}" id="century-${i}" class="btn btn-secondary">${gamedata[i].title}</button>`;
                document.getElementById(`century-${i}`).onclick=(e)=>{changeCentury(e.target.getAttribute('name'))};
            }
        gamePaused=false;
    },(err)=>{console.log("FETCH ERROR",err);gamePaused=false;})
}

// console.log(processGamedata(gamedata));
// uploadData(processGamedata(gamedata)).then((data)=>{console.log(data)});